/**
 * 
 */
package mx.files;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

/**
 * @author v1ctor
 * 
 */
public class FileManager {

	/**
	 * 
	 */
	private FileManager() {
	}

	/**
	 * Colectar un album en la tarjeta de memoria externa
	 * 
	 * @param album
	 * @return
	 */
	private static File getRootAlbum(String album) {
		File file = new File(
				Environment
						.getExternalStoragePublicDirectory(
								Environment.DIRECTORY_PICTURES), album);
		if (!file.mkdirs()) {
			Log.e("getAlbum", "Directorio no creado");
		}
		return file;
	}

	/**
	 * Para saber si el ambiente para guardar imagenes está disponible
	 * 
	 * @return cuando esta disponible o no
	 */
	private static boolean isStorageAvailable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		}
		return false;
	}

	/**
	 * Salva uina imagen con un bitmap y el pathname
	 * 
	 * @param bm
	 * @param imageFileName
	 * @return
	 */
	public static boolean saveImage(Bitmap bm, String imageFileName) {

		try {

			if (isStorageAvailable()) {
				File file = FileManager.getRootAlbum(Files.ROOT_DIRECTORY);

				if (file != null) {
					FileOutputStream stream;
					stream = new FileOutputStream(file.getAbsolutePath() + "/"
							+ imageFileName);

					bm.compress(CompressFormat.JPEG, 100, stream);

					stream.flush();
					stream.close();
					return true;
				}
			}

		} catch (FileNotFoundException e) {
			Log.e("saveImage", e.toString());

		} catch (IOException e) {
			Log.e("saveImage", e.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * Obtiene una bitmap de una imagen guardada.
	 * 
	 * @param imageFileName
	 * @return
	 */
	public static Bitmap retrieveImage(String imageFileName) {

		try {

			if (isStorageAvailable()) {
				File file = FileManager.getRootAlbum(Files.ROOT_DIRECTORY);

				if (file != null) {

					return BitmapFactory.decodeFile(file.getAbsolutePath()
							+ "/" + imageFileName);
				}
			}

		} catch (Exception e) {
			Log.e("retrieveImage", e.toString());
			e.printStackTrace();
		}

		return null;
	}

}
